import React, { useEffect, useState } from 'react';
import {
  Input,
  Button,
  Typography,
  Pagination,
  Table,
  Row,
  Col,
  Select,
  Card,
  Drawer,
  Checkbox,
  Form,
  Tag,
  Popover,
  Alert,
  Space,
} from 'antd';
import CryptoJS from 'crypto-js';
import jsonp from 'jsonp';
import TranslationResult from './TranslationResult'; // Import TranslationResult component
import { SettingOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const { Title, Paragraph } = Typography;

const data = []; // 请注意，您需要从数据库中获取数据并将其填充到此数组中

const Translation = () => {
  const [query, setQuery] = useState('');
  const [translation, setTranslation] = useState(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [data, setData] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [columns, setColumns] = useState([
    {
      title: '单词',
      dataIndex: 'word',
      width: 100,
      key: 'word',
    },
    {
      title: '词性',
      dataIndex: 'partOfSpeech',
      key: 'partOfSpeech',
      width: 100,
      render: partOfSpeech => (
        <span>
          {partOfSpeech.split(',').map(pos => {
            let color;
            switch (pos.trim()) {
              case 'n.':
                color = 'geekblue';
                break;
              case 'v.':
                color = 'green';
                break;
              case 'vi.':
                color = 'cyan';
                break;
              case 'vt.':
                color = 'purple';
                break;
              case 'adj.':
                color = 'volcano';
                break;
              case 'adv.':
                color = 'gold';
                break;
              case 'conj.':
                color = 'magenta';
                break;
              case 'prep.':
                color = 'red';
                break;
              case 'pron.':
                color = 'lime';
                break;
              case 'int.':
                color = 'orange';
                break;

              default:
                color = 'blue';
            }
            return (
              <Tag
                color={color}
                key={pos}>
                {pos}
              </Tag>
            );
          })}
        </span>
      ),
    },
    {
      title: '词义',
      width: 500,
      dataIndex: 'translation',
      key: 'translation',
    },
    {
      title: '标签',
      width: 100,
      dataIndex: 'tag',
      key: 'tag',
      render: tag => (
        <>
          {tag.split(',').map(t => (
            <Tag
              color='blue'
              key={t}>
              {t.trim()}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '查询次数',
      width: 50,
      dataIndex: 'searchCount',
      key: 'searchCount',
    },
    {
      title: '操作',
      width: 150,
      key: 'action',
      render: (text, record) => (
        <Space size='middle'>
          <Button
            type='primary'
            onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button
            type='danger'
            onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]);
  const appKey = '035565f09d622da4';
  const key = 'RJzx3EW8wHTUqUFMggeunHkFGSkbDXYG';
  const handleEdit = record => {
    console.log('Edit:', record);
    // 在这里，您可以执行相应的编辑操作，例如弹出一个模态框让用户编辑单词信息
  };
  const handleShowSizeChange = (current, size) => {
    setPageSize(size);
    // 如果需要，你还可以将当前页重置为1
    // setCurrentPage(1);
  };

  const handleDelete = record => {
    console.log('Delete:', record);
    // 在这里，您可以执行相应的删除操作，例如向后端发送请求以删除指定的单词
  };
  useEffect(() => {
    fetch('http://localhost:29157/api/words/list')
      .then(response => response.json())
      .then(response => {
        if (response.status) {
          setData(response.data.words);
        } else {
          console.error('Error fetching words:', response.error);
        }
      })
      .catch(error => console.error('Error fetching words:', error));
  }, []);

  // ...省略 handleTranslate 和 truncate 函数，保持不变
  const handleTranslate = () => {
    const salt = new Date().getTime();
    const curtime = Math.round(new Date().getTime() / 1000);
    const str1 = appKey + truncate(query) + salt + curtime + key;
    const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);

    const from = 'en';
    const to = 'zh-CHS';

    const url = `http://openapi.youdao.com/api?q=${encodeURIComponent(
      query
    )}&appKey=${appKey}&salt=${salt}&from=${from}&to=${to}&sign=${sign}&signType=v3&curtime=${curtime}`;

    jsonp(url, { param: 'callback' }, (err, data) => {
      if (err) {
        console.error('Error:', err);
      } else {
        setTranslation(data);
      }
    });
  };
  const truncate = q => {
    const len = q.length;
    if (len <= 20) return q;
    return q.substring(0, 10) + len + q.substring(len - 10, len);
  };
  const showDrawer = () => {
    if (
      translation &&
      translation.errorCode === '0' &&
      translation.translation[0]
    ) {
      setDrawerVisible(true);
    } else {
      // 提示用户先查询词汇或检查查询结果
      alert('请先查询词汇并确保翻译结果正确');
    }
  };

  const onClose = () => {
    setDrawerVisible(false);
  };
  const extractPartOfSpeech = text => {
    const regex = /(^|\s)[a-z]+(\.|,)/gi;
    const matches = text.match(regex);
    if (matches) {
      return matches.map(match => match.trim()).join(', ');
    }
    return '';
  };

  const partOfSpeech = extractPartOfSpeech(
    translation && translation.basic && translation.basic.explains
      ? translation.basic.explains.join(', ')
      : ''
  );

  const onFinish = values => {
    console.log('Received values of form: ', values);

    const wordData = {
      word: translation.query,
      translation:
        translation.basic && translation.basic.explains
          ? translation.basic.explains.join(', ')
          : '',
      partOfSpeech: partOfSpeech,
      tag: values.tags ? values.tags.join(',') : '',
      type: translation?.basic?.exam_type?.toString() || '', // 如果需要设定类型，请在这里添加逻辑
      remarks: values.note || '',
    };

    // 将 wordData 发送给后端
    fetch('http://localhost:29157/api/words/push', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(wordData),
    })
      .then(response => {
        if (response.ok) {
          alert('单词已成功添加到数据库');
        } else {
          alert('添加失败，请稍后再试');
        }
      })
      .catch(error => {
        console.error('Error:', error);
      });

    onClose();
  };

  const handlePageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  const handleColumnToggle = columnKey => {
    setColumns(prevColumns =>
      prevColumns.map(column =>
        column.key === columnKey
          ? { ...column, hidden: !column.hidden }
          : column
      )
    );
  };
  const columnSelector = (
    <div>
      <h4>列选择器：</h4>
      {columns.map(column => (
        <Checkbox
          key={column.key}
          checked={!column.hidden}
          onChange={() => handleColumnToggle(column.key)}>
          {column.title}
        </Checkbox>
      ))}
    </div>
  );
  const visibleColumns = columns.filter(column => !column.hidden);
  return (
    <div>
      <Card>
        <Row>
          <Col span={12}>
            <Title
              level={2}
              style={{ textAlign: 'center' }}>
              有道智云文本翻译
            </Title>
            <Paragraph>
              通过有道 API
              进行词汇翻译，并且把词汇入库，当再次遇到这不会的词时可以重复入库，系统将帮你统计遭遇最多次的生词。
            </Paragraph>
            <Paragraph>
              1.点击翻译，翻译结果出现在右侧
              <br />
              2.点击入库，将翻译结果存放到数据库中。
            </Paragraph>
            <TextArea
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder='请输入需要翻译的文本'
              autoSize={{ minRows: 3, maxRows: 6 }}
            />
            <Button
              onClick={handleTranslate}
              type='primary'
              style={{ marginTop: '10px' }}>
              翻译
            </Button>
            <Button
              onClick={showDrawer}
              type='primary'
              style={{ marginTop: '10px', marginLeft: '10px' }}>
              词汇入库
            </Button>
            <Drawer
              title='补充单词信息'
              placement='right'
              width={400}
              onClose={onClose}
              visible={drawerVisible}>
              <Alert
                style={{ width: '100%', height: '100px' }}
                message={'注意'}
                description={
                  <>
                    <span>
                      如果单词已经存在，这里的类型和备注配置将不会生效，请在表格编辑按钮处进行修改
                    </span>
                  </>
                }
              />
              <Form
                layout='vertical'
                onFinish={onFinish}>
                <Form.Item
                  label='标签'
                  name='tags'>
                  <Select
                    mode='tags'
                    placeholder='请输入标签'
                    tokenSeparators={[',', '，']}>
                    {/* 如果需要预定义一些标签，可以在这里添加 <Option> 组件 */}
                  </Select>
                </Form.Item>
                <Form.Item
                  label='备注'
                  name='note'>
                  <TextArea
                    placeholder='请输入备注（可选）'
                    autoSize={{ minRows: 3, maxRows: 6 }}
                  />
                </Form.Item>
                <Form.Item>
                  <Button
                    type='primary'
                    htmlType='submit'>
                    提交
                  </Button>
                </Form.Item>
              </Form>
            </Drawer>
          </Col>
          <Col span={12}>
            {translation && (
              <TranslationResult
                data={translation}
                style={{ marginTop: '10px' }}
              />
            )}
          </Col>
        </Row>
      </Card>

      <Table
        columns={visibleColumns}
        dataSource={data}
        rowKey='id'
        style={{ marginTop: '20px' }}
        pagination={{ pageSize: pageSize, current: currentPage }}
      />
      <Row>
        <Col>
          <Popover
            content={columnSelector}
            title='选择显示的列'
            trigger='click'
            placement='bottomRight'>
            <Button
              icon={<SettingOutlined />}
              type='primary'
              style={{ marginBottom: '20px' }}>
              列选择器
            </Button>
          </Popover>
        </Col>
        <Col>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={data?.length || 0}
            onChange={handlePageChange}
            onShowSizeChange={handleShowSizeChange}
            showSizeChanger={true}
            pageSizeOptions={['5', '10', '20']}
            style={{ marginTop: '20px' }}
          />
        </Col>
      </Row>
    </div>
  );
};

export default Translation;
